package com.study.epay.utils;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.CertAlipayRequest;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.request.AlipayTradePayRequest;
import com.alipay.api.response.AlipayTradePayResponse;
import com.study.epay.config.AliPayProperties;
import com.study.epay.dto.AliPayDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.UUID;

/**
 * @author 朝花不迟暮
 * @version 1.0
 * @date 2020/10/17 17:55
 */
@Component
@Slf4j
public class AliPayUtil
{
    @Autowired
    private AliPayProperties alipayProperties;

    /**
     * 支付接口
     *
     * @param aliPayDto 封装的支付宝入参
     * @return 返回支付结果
     * @throws AlipayApiException 抛出异常
     */
    public String pay(AliPayDto aliPayDto) throws AlipayApiException
    {
       /* //构造client
        CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
        //设置网关地址
        certAlipayRequest.setServerUrl(alipayProperties.getGATEWAY_URL());
        //设置应用Id
        certAlipayRequest.setAppId(alipayProperties.getAPP_ID());
        //设置应用私钥
        certAlipayRequest.setPrivateKey(alipayProperties.getPRIVATE_KEY());
        //设置请求格式，固定值json
        certAlipayRequest.setFormat("json");
        //设置字符集
        certAlipayRequest.setCharset(alipayProperties.getCHARSET());
        //设置签名类型
        certAlipayRequest.setSignType(alipayProperties.getSIGN_TYPE());
        //设置应用公钥证书路径
        certAlipayRequest.setCertPath(alipayProperties.getAPP_CERT_PATH());
        //设置支付宝公钥证书路径
        certAlipayRequest.setAlipayPublicCertPath(alipayProperties.getALIPAY_CERT_PATH());
        //设置支付宝根证书路径
        certAlipayRequest.setRootCertPath(alipayProperties.getALIPAY_ROOT_CERT_PATH());

        AlipayClient alipayClient = new DefaultAlipayClient(certAlipayRequest);

        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();

        AlipayTradePagePayModel model = new AlipayTradePagePayModel();
        model.setOutTradeNo("20150320010101001");
        model.setProductCode("FAST_INSTANT_TRADE_PAY");
        model.setTotalAmount("88.88");
        model.setSubject("Iphone6 16G");
        GoodsDetail goodsDetail = new GoodsDetail();
        goodsDetail.setGoodsId("apple-01");
        goodsDetail.setGoodsName("ipad");
        goodsDetail.setQuantity(1L);
        goodsDetail.setPrice("2000");
        ArrayList<GoodsDetail> list = new ArrayList<>();
        list.add(goodsDetail);
        model.setGoodsDetail(list);
        model.setMerchantOrderNo("2088000603999128");
        model.setQrPayMode("2");
        InvoiceInfo invoiceInfo = new InvoiceInfo();
        invoiceInfo.setDetails("[{\"code\":\"100294400\",\"name\":\"服饰\",\"num\":\"2\",\"sumPrice\":\"200.00\",\"taxRate\":\"6%\"}]");
        InvoiceKeyInfo invoiceKeyInfo = new InvoiceKeyInfo();
        invoiceKeyInfo.setIsSupportInvoice(true);
        invoiceKeyInfo.setInvoiceMerchantName("ABC|003");
        invoiceKeyInfo.setTaxNum("1464888883494");
        invoiceInfo.setKeyInfo(invoiceKeyInfo);
        model.setInvoiceInfo(invoiceInfo);
//        request.setBizContent("{" +
//                "\"out_trade_no\":\"20150320010101001\"," +
//                "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"," +
//                "\"total_amount\":88.88," +
//                "\"subject\":\"Iphone6 16G\"," +
//                "\"body\":\"Iphone6 16G\"," +
//                "\"time_expire\":\"2016-12-31 10:05:01\"," +
//                "      \"goods_detail\":[{" +
//                "        \"goods_id\":\"apple-01\"," +
//                "\"alipay_goods_id\":\"20010001\"," +
//                "\"goods_name\":\"ipad\"," +
//                "\"quantity\":1," +
//                "\"price\":2000," +
//                "\"goods_category\":\"34543238\"," +
//                "\"categories_tree\":\"124868003|126232002|126252004\"," +
//                "\"body\":\"特价手机\"," +
//                "\"show_url\":\"http://www.alipay.com/xxx.jpg\"" +
//                "        }]," +
//                "\"passback_params\":\"merchantBizType%3d3C%26merchantBizNo%3d2016010101111\"," +
//                "\"extend_params\":{" +
//                "\"sys_service_provider_id\":\"2088511833207846\"," +
//                "\"hb_fq_num\":\"3\"," +
//                "\"hb_fq_seller_percent\":\"100\"," +
//                "\"industry_reflux_info\":\"{\\\\\\\"scene_code\\\\\\\":\\\\\\\"metro_tradeorder\\\\\\\",\\\\\\\"channel\\\\\\\":\\\\\\\"xxxx\\\\\\\",\\\\\\\"scene_data\\\\\\\":{\\\\\\\"asset_name\\\\\\\":\\\\\\\"ALIPAY\\\\\\\"}}\"," +
//                "\"card_type\":\"S0JP0000\"" +
//                "    }," +
//                "\"goods_type\":\"0\"," +
//                "\"timeout_express\":\"90m\"," +
//                "\"promo_params\":\"{\\\"storeIdType\\\":\\\"1\\\"}\"," +
//                "\"royalty_info\":{" +
//                "\"royalty_type\":\"ROYALTY\"," +
//                "        \"royalty_detail_infos\":[{" +
//                "          \"serial_no\":1," +
//                "\"trans_in_type\":\"userId\"," +
//                "\"batch_no\":\"123\"," +
//                "\"out_relation_id\":\"20131124001\"," +
//                "\"trans_out_type\":\"userId\"," +
//                "\"trans_out\":\"2088101126765726\"," +
//                "\"trans_in\":\"2088101126708402\"," +
//                "\"amount\":0.1," +
//                "\"desc\":\"分账测试1\"," +
//                "\"amount_percentage\":\"100\"" +
//                "          }]" +
//                "    }," +
//                "\"sub_merchant\":{" +
//                "\"merchant_id\":\"2088000603999128\"," +
//                "\"merchant_type\":\"alipay: 支付宝分配的间连商户编号, merchant: 商户端的间连商户编号\"" +
//                "    }," +
//                "\"merchant_order_no\":\"20161008001\"," +
//                "\"enable_pay_channels\":\"pcredit,moneyFund,debitCardExpress\"," +
//                "\"store_id\":\"NJ_001\"," +
//                "\"disable_pay_channels\":\"pcredit,moneyFund,debitCardExpress\"," +
//                "\"qr_pay_mode\":\"1\"," +
//                "\"qrcode_width\":100," +
//                "\"settle_info\":{" +
//                "        \"settle_detail_infos\":[{" +
//                "          \"trans_in_type\":\"cardAliasNo\"," +
//                "\"trans_in\":\"A0001\"," +
//                "\"summary_dimension\":\"A0001\"," +
//                "\"settle_entity_id\":\"2088xxxxx;ST_0001\"," +
//                "\"settle_entity_type\":\"SecondMerchant、Store\"," +
//                "\"amount\":0.1" +
//                "          }]," +
//                "\"settle_period_time\":\"7d\"" +
//                "    }," +
//                "\"invoice_info\":{" +
//                "\"key_info\":{" +
//                "\"is_support_invoice\":true," +
//                "\"invoice_merchant_name\":\"ABC|003\"," +
//                "\"tax_num\":\"1464888883494\"" +
//                "      }," +
//                "\"details\":\"[{\\\"code\\\":\\\"100294400\\\",\\\"name\\\":\\\"服饰\\\",\\\"num\\\":\\\"2\\\",\\\"sumPrice\\\":\\\"200.00\\\",\\\"taxRate\\\":\\\"6%\\\"}]\"" +
//                "    }," +
//                "\"agreement_sign_params\":{" +
//                "\"personal_product_code\":\"GENERAL_WITHHOLDING_P\"," +
//                "\"sign_scene\":\"INDUSTRY|CARRENTAL\"," +
//                "\"external_agreement_no\":\"test\"," +
//                "\"external_logon_id\":\"13852852877\"," +
//                "\"sign_validity_period\":\"2m\"," +
//                "\"third_party_type\":\"PARTNER\"," +
//                "\"buckle_app_id\":\"1001164\"," +
//                "\"buckle_merchant_id\":\"268820000000414397785\"," +
//                "\"promo_params\":\"{\\\"key\\\",\\\"value\\\"}\"" +
//                "    }," +
//                "\"integration_type\":\"PCWEB\"," +
//                "\"request_from_url\":\"https://\"," +
//                "\"business_params\":\"{\\\"data\\\":\\\"123\\\"}\"," +
//                "\"ext_user_info\":{" +
//                "\"name\":\"李明\"," +
//                "\"mobile\":\"16587658765\"," +
//                "\"cert_type\":\"IDENTITY_CARD\"," +
//                "\"cert_no\":\"362334768769238881\"," +
//                "\"min_age\":\"18\"," +
//                "\"fix_buyer\":\"F\"," +
//                "\"need_check_info\":\"F\"" +
//                "    }" +
//                "  }");
        request.setBizModel(model);
        AlipayTradePagePayResponse response = alipayClient.pageExecute(request);

        if(response.isSuccess()){
            System.out.println("调用成功");
            System.out.println(response.getBody());
            return response.getBody();
        } else {
            System.out.println("调用失败");
        }
        return "调用失败";*/

        //构造client
        CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
        //设置网关地址
        certAlipayRequest.setServerUrl(alipayProperties.getGATEWAY_URL());
        //设置应用Id
        certAlipayRequest.setAppId(alipayProperties.getAPP_ID());
        //设置应用私钥
        certAlipayRequest.setPrivateKey(alipayProperties.getPRIVATE_KEY());
        //设置请求格式，固定值json
        certAlipayRequest.setFormat("json");
        //设置字符集
        certAlipayRequest.setCharset(alipayProperties.getCHARSET());
        //设置签名类型
        certAlipayRequest.setSignType(alipayProperties.getSIGN_TYPE());
        //设置应用公钥证书路径
        certAlipayRequest.setCertPath(alipayProperties.getAPP_CERT_PATH());
        //设置支付宝公钥证书路径
        certAlipayRequest.setAlipayPublicCertPath(alipayProperties.getALIPAY_CERT_PATH());
        //设置支付宝根证书路径
        certAlipayRequest.setRootCertPath(alipayProperties.getALIPAY_ROOT_CERT_PATH());

        AlipayClient alipayClient = new DefaultAlipayClient(certAlipayRequest);

        //构造API请求
        AlipayTradePayRequest request = new AlipayTradePayRequest();

        //SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
        AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();

        model.setBody("我是测试数据");
        model.setSubject("App支付测试Java");
        model.setOutTradeNo(UUID.randomUUID().toString());
        model.setTimeoutExpress("30m");
        model.setTotalAmount("0.01");
        model.setProductCode("QUICK_MSECURITY_PAY");
        request.setBizModel(model);

        // 页面跳转同步通知页面路径
        request.setReturnUrl(alipayProperties.getRETURN_URL());
        // 服务器异步通知页面路径
        request.setNotifyUrl(alipayProperties.getNOTIFY_URL());
        // 封装参数
        request.setBizContent(JSON.toJSONString(aliPayDto));

        AlipayTradePayResponse response = null;
        try
        {
            //这里和普通的接口调用不同，使用的是sdkExecute
            response = alipayClient.certificateExecute(request);
            log.info("返回的response.getBody：{}",response.getBody());
            if(response.isSuccess()){
                System.out.println("调用成功");
                return response.getBody();
            } else {
                System.out.println("调用失败");
                return "调用失败";
            }

        } catch (AlipayApiException e)
        {
            e.printStackTrace();
        }
        return null;
    }

}
